package com.gameShare.entity.vo

import com.gameShare.enums.misc.PageSizeEnum
import com.gameShare.enums.misc.ResponseCodeEnum
import com.gameShare.exceptions.BusinessException

class PageVo<T> (val pageNo : Int, val countTotal : Int, val pageSize : Int,val pageTotal : Int, val data : List<T>?){

    companion object{

        /**
         * 生产pageVo对象
         *
         * @param T pageVo的data类型
         * @param pageNo 页码
         * @param pageSize 页面大小 最大不能超过PageSizeEnum.MAX_SIZE
         * @param selectTotalCountFunc 查询页面大小方法
         * @param selectDataFunc 查询页面数据方法
         * @return pageVo对象 T类型可能为null
         */
        fun <T> generatePageVo(pageNo : Int?,
                           pageSize : Int?,
                           selectTotalCountFunc : () -> Int,
                           selectDataFunc : (start: Int, end : Int) -> List<T?> ): PageVo<T?> {
            val effectivePageSize = pageSize ?: PageSizeEnum.SIZE10.size
            if (effectivePageSize > PageSizeEnum.SIZE_MAX.size){
                throw BusinessException(ResponseCodeEnum.ARGUMENT_ERROR.code, "页面大小超出最大值")
            }

            val pageNumber =
                if (pageNo == null || pageNo <= 0) 1
                else pageNo

            val countTotal = selectTotalCountFunc()
            val start = (pageNumber - 1) * effectivePageSize
            val end = start + effectivePageSize
            val resultData : List<T?> = selectDataFunc(start, end)
            val pageTotal = when {
                countTotal <= 0 -> 0
                countTotal % effectivePageSize == 0 -> countTotal / effectivePageSize
                else -> countTotal / effectivePageSize + 1
            }
            return PageVo(pageNumber, countTotal, effectivePageSize, pageTotal, resultData)
        }
    }
}